<?php

/**
 * @copyright (c) 2011
 */
App::uses('AppModel', 'Model');

class StudentUser extends AppModel {

    var $name = 'StudentUser';
    
    public $belongsTo = array(
        'Program' => array(
            'className' => 'Program',
            'foreignKey' => 'program_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );
    
    public $hasMany = array(
        'Transaction' => array(
            'className' => 'Transaction',
            'foreignKey' => 'student_user_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'StudentNotification' => array(
            'className' => 'StudentNotification',
            'foreignKey' => 'student_user_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'StudentServiceRequest' => array(
            'className' => 'StudentServiceRequest',
            'foreignKey' => 'student_user_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        ),
        'ForgotPassToken' => array(
            'className' => 'ForgotPassToken',
            'foreignKey' => 'student_user_id',
            'conditions' => '',
            'fields' => '',
            'order' => ''
        )
    );

   /* public function beforeSave($options = array()) {
        if (isset($this->data)) {
            $this->sanitize($this->data);
        }
        return true;
    }*/

    public function save($data = null,$validate = true, $fieldList = array()) {
        $s = $this->sanitize($data);
        return parent::save($s);
    }

    function login($username = null, $password = null) {
        $password = md5($password);

        $result = $this->find('first', array(
            'conditions' => array('username' => $username, 'password' => $password),
            'recursive' => -1)
        );

        if($result) {
            $active = $result['StudentUser']['active'];
            if($active == 'n') { /** User is disable, Logout */
                return array('status' => false, 'msg' => 'Account is disabled');
            } else {
                return array('status' => true, 'msg' => 'Account Verified', 'data' => $result);
            }
        } else {
            return array('status' => false, 'msg' => 'Invalid login credentials');
        }
    }


    function verify_account($username = null,$email = null,$cellphone = null) {
        $result = $this->find('first', array(
                'conditions' => array('username' => $username, 'OR'=>array('email'=>$email,'cellphone'=>$cellphone)),
                'recursive' => -1)
        );

        if($result) {
            $active = $result['StudentUser']['active'];
            if($active == 'n') { /** User is disable, Logout */
                return array('status' => false, 'msg' => 'Account is disabled. Please go to the academic office to have your account enabled and password reset, after your password is set, make sure you update your email and cellphone.');
            } else {
                return array('status' => true, 'msg' => 'Username Verified', 'data' => $result);
            }
        } else {
            return array('status' => false, 'msg' => 'Username/Email/Cellphone is Invalid. Please go to the academic office to have your password reset, after your password is set, make sure you update your email and cellphone.');
        }
    }


    /**
     * This function retrieves all the users from the database tables users.
     * @name getAllUsers
     * @param void
     * @return mixed. Array containing the data retrieved.
     * @access public
     */
    function getAllUsers() {
        # fetch the data and return it.
        return $this->find('all', array('conditions' => array('deleted' => 'n'), 'recursive' => -1));
    }

    /**
     * This function retrieves the user data based upon his/her id
     * @name getUserById
     * @param string $userId string holding the user id.his parameter is defaulted to null.
     * When it is null it means that cake is going to use the ActiveRecord system to retrieve the data.
     * @return mixed. Array containing the user data.
     * @access public
     */
    function getUserById($userId = null, $recursive=1) {
        $conditions = array(
            'StudentUser.id' => $userId,
            'StudentUser.deleted' => 'n'
        );
        # fetch the specific data from the server and retrun it.
        return $this->find('first', array('conditions' => $conditions, 'recursive' => $recursive));
    }

    # User Data manipulation functions
    /**
     * This function retrieves the user by his login name
     * @name getUserByLoginName
     * @param string $loginName
     * @return array of data containing the login name and the user password
     * @access public
     */

    function getUserByLoginName($loginName = null) {
        # search condition
        $conditions = array(
            'StudentUser.username' => $loginName,
            'StudentUser.deleted' => 'n'
        );
        # fetch the specific data from the server and retrun it.
        return $this->find('first', array('conditions' => $conditions, 'recursive' => 1));
    }


    function creditAccount($user_id=0, $amount=0.00) {
        # search condition
        $res = $this->_modifyAccountBalance($user_id,$amount,'credit');
        if($res){
            return true;
        }
        else{
            return $res;
        }
    }

    function debitAccount($user_id=0, $amount=0.00) {
        # search condition
        $res = $this->_modifyAccountBalance($user_id,$amount,'debit');
        if($res){
            return true;
        }
        else{
            return $res;
        }
    }

    function _modifyAccountBalance($id,$amount,$type){
        $this->id = $id;
        
        if($type == 'credit'){
            $res = $this->save(array(
                'id'=>$id,
                'account_balance'=>doubleval($this->field('account_balance')) + doubleval($amount)
            ));
        }
        else{//debit
            $res = $this->save(array(
                'id'=>$id,
                'account_balance'=>doubleval($this->field('account_balance')) - doubleval($amount)
            ));
        }

        return $res;
    }

    function getRawBills($index_number,$current_academic_year){
        $result = $this->getBills($index_number,$current_academic_year);
        $bill_data = array();
        $total_bill = 0.00;
        $total_paid = 0.00;
        $total_owed = 0.00;
        foreach($result as $key => $value){
            if(is_int($key)){
                $bill_data[$key]= $value;
                $total_bill = $total_bill + intval($value['amount']);
                $total_paid = $total_paid + intval($value['paid']);
                $total_owed = $total_owed + intval($value['owed']);
            }
        }

        return array(
            'data'=>$bill_data,
            'total_bill'=>$total_bill,
            'total_paid'=>$total_paid,
            'total_owed'=>$total_owed
        );
    }

    function getBills($index_number,$current_academic_year){
        //debug($current_academic_year);
        $Fee = ClassRegistry::init('Fee');
        $TransactionItem = ClassRegistry::init('TransactionItem');
        $bills_data = $Fee->find('all',array(
            'conditions'=>array('Fee.academic_year'=>$current_academic_year, 'Fee.index_number'=>$index_number ),
            'contain' => array('FeeType'),
            'recursive'=>2
        ));

        $cart = array();
        $temp = array();
        foreach($bills_data as $value){
            $fee_id = $value['Fee']['id'];
            $fee_type_id = $value['FeeType']['id'];
            $fee_cat = $value['FeeType']['fee_category'];
            $fee_description = $value['FeeType']['description'];
            $fee_amt = doubleval($value['Fee']['amount']);
            $trans_type_to_use = $value['Fee']['trans_type_to_use'];
            $trans_items = $TransactionItem->find('all',array(
                'conditions'=>array('fee_id'=>$fee_id),
                'recursive'=>-1
            ));
            if($trans_items){
                $total_pay = 0.00;
                foreach($trans_items as $item){
                    $credit_amt = doubleval($item['TransactionItem']['credit_amt']);
                    $total_pay = $total_pay + $credit_amt;
                }
                $paid = $total_pay;
                $owed = $fee_amt - $paid;
            }
            else{
                $paid = 0.00;
                $owed = $fee_amt - $paid;
            }

            $cart_item = array(
                'id'=>$fee_id,
                'fee_type_id'=>$fee_type_id,
                'fee_category'=>$fee_cat,
                'class'=>'',
                'description'=>$fee_description,
                'trans_type_to_use' => $trans_type_to_use,
                'amount'=> $fee_amt,
                'paid'=> $paid,
                'owed'=> $owed,
                'button'=>'y'
            );
            $temp[$fee_cat][]=$cart_item;
        }

        foreach($temp as $fee_cat => $arr){
            $cart[''.$fee_cat.''] = array(
                'id'=>'',
                'fee_type_id'=>'',
                'fee_category'=>''.$fee_cat.'',
                'class'=>'nav-header',
                'description'=>$fee_cat,
                'trans_type_to_use'=>'',
                'amount'=>'BILL',
                'paid'=>'PAID',
                'owed'=>'OWED',
                'button'=>'n'
            );
            foreach($arr as $val){
                $cart[$val['id']] = array(
                    'id'=>$val['id'],
                    'fee_type_id'=>$val['fee_type_id'],
                    'fee_category'=>$val['fee_category'],
                    'class'=>'',
                    'description'=>$val['description'],
                    'trans_type_to_use'=>$val['trans_type_to_use'],
                    'amount'=> $val['amount'],
                    'paid'=> $val['paid'],
                    'owed'=> $val['owed'],
                    'button'=>'y'
                );
            }
        }

        return $cart;
    }


}